#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myerror.h"

static void err_doit(int ,int, const char *, va_list);

/**
 * err_sys - fatal error related to system call
 *           print a message and terminate
 * */
void err_sys(const char *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
    err_doit(1, errno, fmt, ap);
    va_end(ap);
    exit(1);
}

static void err_doit(int errnoflag, int error, const char *fmt, va_list ap)
{
    char buf[1024] = {0};
    vsnprintf(buf, 1024, fmt, ap);
    int len = strlen(buf);
    if (errnoflag)
        snprintf(buf + len, 1024 - len, 
                ":%s", strerror(error));
    len = strlen(buf);
    buf[len] = '\n';
    fflush(stdout); //in case stdout and stderr are the same
    fputs(buf, stderr);
    fflush(NULL);   //fflushed all stdio output streams
}
